4.What is JSON and its common operations

S
Soumya Jana
Sun Feb 23 2025

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write for humans and easy to parse and generate for machines. It is widely used for data exchange between a server and a web application, as well as for configuration files, APIs, and database storage.

JSON represents data in key-value pairs, using:

  • Objects (enclosed in {}) with key-value pairs.
  • Arrays (enclosed in []) containing multiple values.

Example of JSON:

json
{ "name": "John Doe", "age": 30, "isStudent": false, "hobbies": ["reading", "gaming", "traveling"], "address": { "city": "New York", "zip": "10001" } }

Common JSON Operations:

1. Parsing JSON (String to Object)

Converting a JSON string into a JavaScript object.

javascript
const jsonString = '{"name":"John", "age":30}'; const obj = JSON.parse(jsonString); console.log(obj.name); // Output: John

2. Stringifying JSON (Object to String)

Converting a JavaScript object into a JSON string.

javascript
const obj = { name: "John", age: 30 }; const jsonString = JSON.stringify(obj); console.log(jsonString); // Output: {"name":"John","age":30}

3. Accessing JSON Data

Once parsed, JSON data can be accessed like a normal JavaScript object.

javascript
const person = { name: "Alice", age: 25, address: { city: "Los Angeles", zip: "90001" } }; console.log(person.name); // Output: Alice console.log(person.address.city); // Output: Los Angeles

4. Modifying JSON Data

You can modify JSON objects directly.

javascript
person.age = 26; person.address.city = "San Francisco"; console.log(person);

5. Adding and Removing Properties

  • Adding a property
javascript
person.email = "alice@example.com"; console.log(person);
  • Removing a property
javascript
delete person.age; console.log(person);

6. Looping Through JSON Data

javascript
for (let key in person) { console.log(`${key}: ${person[key]}`); }

7. Handling Nested JSON Data

javascript
const data = { users: [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" } ] }; console.log(data.users[1].name); // Output: Bob

Where is JSON Used?

  • APIs: Used for data exchange in web applications.
  • Configuration Files: .json files for storing settings.
  • Databases: NoSQL databases like MongoDB use JSON-like formats.
  • Local Storage: Web storage in browsers (localStorage).

Let me know if you need further details! 🚀

Related Posts:

View All Related Posts
Sign In To Write A Comment
@soumya_jana
2025-02-23T05:05:49.751Z
Hi, this is a test comment.
sign in or verify yourself to reply
@soumya_jana
2025-02-23T05:06:14.674Z
Hi, this is a test reply
@soumya_jana
2025-02-23T05:08:18.529Z
Not so cool
Copyright © 2025 codewithjana.com